﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using HtmlAgilityPack;

namespace WebLayer
{
    public enum LastMessageType { Reserve, Cancel }

    public class LastMessagePage: SiteWebPage
    {
        static Uri GetPageUri(string msgType)
        {
            string baseUri  = "http://sz.speak-up.com.ua/StrefaSluchacza/msg.php?";

            string msg_parameter = "msg=" + msgType;

            TimeSpan delta = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0).ToLocalTime();
            long ms = (long)delta.TotalMilliseconds;

            string strMs = ms.ToString().Substring(5);
            string postfix = new Random().Next(100).ToString();

            string custom_unique_parameter="custom_unique_param="+strMs+postfix;

            return new Uri(baseUri + msg_parameter +"&" + custom_unique_parameter);
        }

        static String GetMessageTypeString(LastMessageType msgType)
        {
            switch(msgType)
            {
                case LastMessageType.Reserve:
                    return "cancel_reservations";
                case LastMessageType.Cancel:
                    return "reservations";                
                default:
                    throw new ArgumentException();
            }
        }

        public LastMessagePage(string msgType) :
            base("LastMessage", GetPageUri(msgType))
        { }

        public LastMessagePage(LastMessageType type):
            base("LastMessage", GetPageUri(GetMessageTypeString(type)))
        {}

        public String Message;

        protected override void OnResponse(System.Net.HttpWebRequest request, System.Net.HttpWebResponse response)
        {
            base.OnResponse(request, response);
            
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(PageContent);

            HtmlNode node = doc.DocumentNode.SelectSingleNode("//text");

            if (node != null)
            {
                Message = node.InnerText;
            }
            else
            {
                Message = PageContent;
            }

            Trace.WriteLine(PageName + ": Message - "+Message);
        }
    }
}
